layui.define(['form', 'laydate', 'formSelects', 'layedit', 'upload'], function (exports) {

    var $ = layui.$
        , layer = layui.layer
        , view = layui.view
        , admin = layui.admin
        , form = layui.form
        , laydate = layui.laydate
        , formSelects = layui.formSelects
        , layedit = layui.layedit
        , upload = layui.upload
        , reForm = {

            editor: {}
            , initForm: function (options) {
                options = options || {};

                form.render(null, options.formLay);

                var toolFun = $.extend({
                    save: function () {
                        $('[lay-filter="' + options.formLay + '-submit"]').click();
                    }
                }, options.toolFun);

                $('#' + options.formLay + '-tool .layui-btn').on('click', function () {
                    var type = $(this).attr('lay-event');
                    toolFun[type] ? toolFun[type].call(this) : '';
                });

                if (options.subUrl) {
                    form.verify(reForm.verify);
                    form.on('submit(' + options.formLay + '-submit)', function (data) {

                        var subData = reForm.getFilterFormData(data, options.formLay);

                        if (typeof options.verify === 'function' && options.verify.call(this, subData) === false)
                            return false;

                        admin.req({
                            url: options.subUrl
                            , type: 'post'
                            , data: subData
                            , loading: options.postLoad !== false ? true : false
                            , tipOk: options.tipOk !== false ? true : false
                            , success: options.success || null
                            , done: options.done ? function (res) {
                                options.done.call(this, $.extend(res, { subData: subData }));
                            } : null
                        });

                        return false;
                    });
                }
            }
            , popupForm: function (options) {

                if (options.width && !isNaN(options.width))
                    options.width = parseInt(options.width) <= 100 ? options.width + '%' : options.width + 'px';
                if (options.height && !isNaN(options.height))
                    options.height = parseInt(options.height) <= 100 ? options.height + '%' : options.height + 'px';

                if (options.formHtml && options.FormItemsData)
                    admin.popup({
                        title: options.title
                        , area: [options.width || '900px', options.height || '700px']
                        , id: 'LAY-popup-' + options.formLay
                        , content: options.formHtml
                        , shadeClose: false
                        , success: function (layero, index) {
                            var initData = typeof options.initData === 'function' ? options.initData.call(this) : options.initData || null;
                            $.each(options.FormItemsData, function (idx, json) {
                                reForm.bindFormHtml(json, initData, options.formLay);
                            });

                            if (initData)
                                reForm.loadFormData(initData, options.formLay);

                            typeof options.formInit === 'function' && options.formInit.call(this, initData);

                            //监听提交
                            var success = options.success;
                            var done = options.done;
                            reForm.initForm($.extend({}, options, {
                                success: function (res) {
                                    typeof success === 'function' && success.call(this, res);
                                }
                                , done: function (res) {
                                    if (options.postLoad)
                                        layer.closeAll('loading');
                                    //view.removeLoad();
                                    layer.close(index);
                                    typeof done === 'function' && done.call(this, res, index);
                                }
                            }));
                        }, end: options.end
                    });
                else if (options.formLay && !options.url) {// && options.sourcePage
                    var subFormNo = options.sourcePage ? options.sourcePage + '-form' : options.formLay;
                    admin.jsonData('/json/form/' + (options.formLay || subFormNo), function (subForm) {
                        var subFormItemsData = admin.stringToObj(subForm);
                        var html = '<form class="layui-form " lay-filter="' + subFormNo + '" id="' + subFormNo + '">'
                            + layui.admin.getFormHtml(subFormItemsData)
                            + (options.sourcePage ? layui.admin.getFormBtn(options.sourcePage, options.buttons ? { Sign: options.buttons } : {}) : '')
                            + '</form>';
                        options.formLay = subFormNo;
                        options.formHtml = html;
                        options.FormItemsData = subFormItemsData;

                        admin.popup({
                            title: options.title
                            , area: [options.width || '900px', options.height || '700px']
                            , id: 'LAY-popup-' + options.formLay
                            , content: html
                            , shadeClose: false
                            , success: function (layero, index) {
                                var initData = typeof options.initData === 'function' ? options.initData.call(this) : options.initData || null;

                                $.each(options.FormItemsData, function (idx, json) {
                                    reForm.bindFormHtml(json, initData, options.formLay);
                                });

                                if (initData)
                                    reForm.loadFormData(initData, options.formLay);

                                typeof options.formInit === 'function' && options.formInit.call(this, initData);

                                //监听提交
                                var success = options.success;
                                var done = options.done;
                                reForm.initForm($.extend({}, options, {
                                    success: function (res) {
                                        typeof success === 'function' && success.call(this, res);
                                    }
                                    , done: function (res) {
                                        layer.close(index);
                                        typeof done === 'function' && done.call(this, res, index);
                                    }
                                }));
                            }, end: options.end
                        });
                    });
                }
                else {
                    admin.popup({
                        title: options.title
                        , area: [options.width || '900px', options.height || '700px']
                        , id: 'LAY-popup-' + options.formLay
                        , shadeClose: false
                        , success: function (layero, index) {
                            view(this.id).render(options.url, typeof options.initData === 'function' ? options.initData.call(this) : options.initData || null).done(function () {
                                reForm.setFormLang(options.formLay);

                                typeof options.formInit === 'function' && options.formInit.call(this, typeof options.initData === 'function' ? options.initData.call(this) : options.initData || null);

                                var success = options.success;
                                var done = options.done;
                                reForm.initForm($.extend({}, options, {
                                    success: function (res) {
                                        typeof success === 'function' && success.call(this, res);
                                    }
                                    , done: function (res) {
                                        layer.close(index);
                                        typeof done === 'function' && done.call(this, res, index);
                                    }
                                }));
                            });
                        }, end: options.end
                    });
                }
            }
            , tblForm: function (options) {
                view(options.tplId).render(options.url, typeof options.initData === 'function' ? options.initData.call(this) : options.initData || null).done(function () {

                    reForm.setFormLang(options.formLay);

                    typeof options.formInit === 'function' && options.formInit.call(this, typeof options.initData === 'function' ? options.initData.call(this) : options.initData || null);

                    //监听提交
                    var success = options.success;
                    reForm.initForm($.extend({}, options, {
                        success: function (res) {
                            typeof success === 'function' && success.call(this, res);
                        }
                        , done: function (res) {
                            typeof done === 'function' && done.call(this, res, index);
                        }
                    }));
                });
            }

            , setFormLang: function (formid, tableid) {
                var formObj = $('[lay-filter="' + formid + '"]');
                if (!formObj.length)
                    formObj = $('#' + formid);
                if (formObj)
                    $('[lay-filter="' + formid + '-submit"]').val(layui.admin.lang ? 'Submit' : '确认');

                admin.getDictionary('page-form-field', tableid || formid, function (d) {
                    $.each(d, function (idx, item) {
                        var text = item['MemberName' + admin.lang];
                        var obj = $(formObj).find('[name="' + item.Member + '"]');

                        if (obj && obj.prop('type') !== 'hidden') {
                            $(obj).parent().prev().hasClass('layui-form-label') ? $(obj).parent().prev().html(text) : '';
                            var tagName = $(obj).prop("tagName");
                            switch (tagName) {
                                case 'SELECT':
                                    $(obj).attr('fieldname', text);
                                    $(obj).children().first().html((admin.lang ? 'Please select ' : '请选择') + text);
                                    break;
                                case 'INPUT':
                                case 'TEXTAREA':
                                    $(obj).attr('fieldname', text);
                                    typeof $(obj).attr('placeholder') !== 'undefined' ? $(obj).attr('placeholder', (admin.lang ? 'Please input ' : '请输入') + text) : '';
                                    break;
                                default:
                                    break;
                            }
                        }
                    });

                });
            }

            , getFilterFormData: function (data, filter) {

                var elem = '[lay-filter="' + filter + '"] ';
                var fields = data.field;


                $(elem + 'input[type=checkbox]:checked').each(function () {
                    if (fields[$(this).attr('name')]) {
                        fields[$(this).attr('name')] += ',' + $(this).val();
                    } else {
                        fields[$(this).attr('name')] = $(this).val();
                    }
                });
                $(elem + 'input[type=password]').each(function () {
                    fields[$(this).attr('name')] = CryptoJS.MD5($(this).val()).toString();
                });
                $(elem + 'input[type=checkbox][lay-skin="switch"]').each(function () {
                    if ($(this).prop('checked')) fields[$(this).attr('name')] = true;
                    if (!$(this).prop('checked')) fields[$(this).attr('name')] = false;
                });

                $(elem + ' textarea[retype="editor"]').each(function () {
                    reForm.editor[$(this).attr('id')].sync();
                    fields[$(this).attr('name')] = reForm.editor[$(this).attr('id')].content();
                });

                $.each(fields, function (k, v) {
                    if (!v && v !== false || $(elem + ' [name="' + k + '"]').closest('[reitemid]').attr('noverify') !== undefined) {
                        delete fields[k];
                    }
                });

                //$(elem + 'input[type=hidden]').each(function () {
                //    fields[$(this).attr('name')] = $(this).val();
                //});

                return fields;
            }
            , getFormData: function (elem) {
                var fields = {};
                var formDate = $(elem).serializeArray();
                $.each(formDate, function () {
                    fields[this.name] = this.value;
                });

                $(elem).find('input[type=password]').each(function () {
                    if ($(this).attr('name'))
                        fields[$(this).attr('name')] = CryptoJS.MD5($(this).val()).toString();
                });

                $(elem).find('input[type=checkbox]:checked').not('[lay-skin="switch"]').each(function () {
                    if ($(this).attr('name')) {
                        if (fields[$(this).attr('name')]) {
                            fields[$(this).attr('name')] += ',' + $(this).val();
                        } else {
                            fields[$(this).attr('name')] = $(this).val();
                        }
                    }
                });

                $(elem).find('input[type=checkbox][lay-skin="switch"]').each(function () {
                    if ($(this).prop('checked')) fields[$(this).attr('name')] = true;
                    if (!$(this).prop('checked')) fields[$(this).attr('name')] = false;
                });

                $(elem).find('textarea[retype="editor"]').each(function () {
                    reForm.editor[$(this).attr('id')].sync();
                    fields[$(this).attr('name')] = reForm.editor[$(this).attr('id')].content();
                });

                $.each(fields, function (k, v) {
                    if (!v && v !== false || $(elem).find('[name="' + k + '"]').closest('[reitemid]').attr('noverify') !== undefined) {
                        delete fields[k];
                    }
                });

                //$(elem + 'input[type=hidden]').each(function () {
                //    fields[$(this).attr('name')] = $(this).val();
                //});

                return fields;
            }
            , loadFormData: function (formData, filter) {
                var elem = '[lay-filter="' + filter + '"]';
                $(elem)[0].reset();
                if (!admin.hasObject(formData)) return;

                elem = '[lay-filter="' + filter + '"] ';//加空格

                $(elem + 'input[type=checkbox]').prop('checked', false);

                form.val(filter, formData);

                $(elem + 'input[type=checkbox][lay-skin="switch"]').each(function () {
                    if (formData[$(this).attr('name')]) $(this).prop('checked', true);
                });

                $(elem + 'input[type=checkbox]').not('[lay-skin="switch"]').each(function () {
                    $(this).prop('checked', false);
                    if (formData[$(this).attr('name')] && formData[$(this).attr('name')].split(',').indexOf($(this).val()) > -1) {
                        $(this).prop('checked', true);
                    }
                });

                $(elem + 'input[type=radio]').each(function () {
                    $(this).prop('checked', false);
                    if (formData[$(this).attr('name')] && formData[$(this).attr('name')].toString() === $(this).val().toString()) {
                        $(this).prop('checked', true);
                    }
                });

                //form.render(null, filter);
            }

            , expandingArea: function (el, fun) {
                if (!$(el).val())
                    el.style.height = 'auto';

                var setStyle = function (el, auto) {
                    if (auto) el.style.height = 'auto';
                    el.style.height = el.scrollHeight + 2 + 'px';
                    typeof fun === 'function' && fun.call(this, el);
                };
                if (el.addEventListener) {
                    el.addEventListener('input', function () {
                        setStyle(el, 1);
                    }, false);
                    setStyle(el);
                } else if (el.attachEvent) {
                    el.attachEvent('propertychange', function () {
                        setStyle(el);
                    });
                    setStyle(el);
                }
            }

            , viewImg: function (imgUrl) {
                reForm.popupForm({
                    title: admin.lang ? 'View Image' : '查看图片'
                    , width: '80%'
                    , height: '85%'
                    , url: '/admin/system/viewImg'
                    , formLay: 'admin-viewImg-form'
                    , initData: { ImgUrl: imgUrl }
                });
            }

            , regular: {
                required: /[\S]+/,
                int: /^-?\d+$/,
                chinese: /^[\u4e00-\u9fa5]+$/,
                email: /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/,
                phone: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
                telephone: /^((0\d{2,3})-?)(\d{7,8})(-(\d{3,}))?$/,
                url: /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/,
                identity: /(^\d{15}$)|(^\d{17}(x|X|\d)$)/,
                dateTime: /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/,
                dateTime1: /^[1-9]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/
            }
            , verify: {
                required: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';
                    var title = $(item).attr('fieldname');
                    title = title ? title : '';

                    if (!value || $.trim(value) === '')
                        return $(item).attr('requiredmsg') ? $(item).attr('requiredmsg') : title + (layui.admin.lang ? " can't be empty." : '不能为空。');

                    value = $.trim(value);

                    var vLen = admin.trimAll(value).length;
                    if (vLen < $(item).attr('minLen'))
                        return title + (layui.admin.lang ? " length should not be less than " : '长度不能小于') + $(item).attr('minLen') + (layui.admin.lang ? '.' : '。');

                    if (vLen > $(item).attr('maxLen'))
                        return title + (layui.admin.lang ? " length should not be greater than " : '长度不能大于') + $(item).attr('maxLen') + (layui.admin.lang ? '.' : '。');

                    var regular = $(item).attr('regular');
                    var regularMsg = $(item).attr('regularMsg' + layui.admin.lang);
                    if (regular && !new RegExp(regular).test(value))
                        return regularMsg ? regularMsg : title + (layui.admin.lang ? ' does not meet the requirements.' : '不符合要求。');
                },
                fillRequired: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value) {
                        value = $.trim(value);

                        var title = $(item).attr('fieldname');
                        title = title ? title : '';

                        var vLen = admin.trimAll(value).length;
                        if (vLen < $(item).attr('minLen'))
                            return title + (layui.admin.lang ? " length should not be less than " : '长度不能小于') + $(item).attr('minLen') + (layui.admin.lang ? '.' : '。');

                        if (vLen > $(item).attr('maxLen'))
                            return title + (layui.admin.lang ? " length should not be greater than " : '长度不能大于') + $(item).attr('maxLen') + (layui.admin.lang ? '.' : '。');

                        var regular = $(item).attr('regular');
                        var regularMsg = $(item).attr('regularMsg' + layui.admin.lang);
                        if (regular && !new RegExp(regular).test(value))
                            return regularMsg ? regularMsg : (layui.admin.lang ? ' does not meet the requirements.' : '不符合要求。');
                    }
                },
                visibleRequired: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if ($(item).is(':visible')) {
                        var title = $(item).attr('fieldname');
                        title = title ? title : '';

                        if (!value || $.trim(value) === '')
                            return $(item).attr('requiredmsg') ? $(item).attr('requiredmsg') : title + (layui.admin.lang ? " can't be empty." : '不能为空。');
                    }
                },
                editor: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';
                    var title = $(item).attr('fieldname');
                    title = title ? title : '';

                    reForm.editor[$(item).attr('id')].sync();
                    value = reForm.editor[$(item).attr('id')].text();

                    if (!value || $.trim(value) === '')
                        return $(item).attr('requiredmsg') ? $(item).attr('requiredmsg') : title + (layui.admin.lang ? " can't be empty." : '不能为空。');

                    value = $.trim(value);

                    var vLen = admin.trimAll(value).length;
                    if (vLen < $(item).attr('minLen'))
                        return title + (layui.admin.lang ? " length should not be less than " : '长度不能小于') + $(item).attr('minLen') + (layui.admin.lang ? '.' : '。');

                    if (vLen > $(item).attr('maxLen'))
                        return title + (layui.admin.lang ? " length should not be greater than " : '长度不能大于') + $(item).attr('maxLen') + (layui.admin.lang ? '.' : '。');

                    var regular = $(item).attr('regular');
                    var regularMsg = $(item).attr('regularMsg' + layui.admin.lang);
                    if (regular && !new RegExp(regular).test(value))
                        return regularMsg ? regularMsg : title + (layui.admin.lang ? ' does not meet the requirements.' : '不符合要求。');
                },
                fillEditor: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    reForm.editor[$(item).attr('id')].sync();
                    value = reForm.editor[$(item).attr('id')].text();

                    if (value) {
                        value = $.trim(value);

                        var title = $(item).attr('fieldname');
                        title = title ? title : '';

                        var vLen = admin.trimAll(value).length;
                        if (vLen < $(item).attr('minLen'))
                            return title + (layui.admin.lang ? " length should not be less than " : '长度不能小于') + $(item).attr('minLen') + (layui.admin.lang ? '.' : '。');

                        if (vLen > $(item).attr('maxLen'))
                            return title + (layui.admin.lang ? " length should not be greater than " : '长度不能大于') + $(item).attr('maxLen') + (layui.admin.lang ? '.' : '。');

                        var regular = $(item).attr('regular');
                        var regularMsg = $(item).attr('regularMsg' + layui.admin.lang);
                        if (regular && !new RegExp(regular).test(value))
                            return regularMsg ? regularMsg : (layui.admin.lang ? ' does not meet the requirements.' : '不符合要求。');
                    }
                },
                latreg: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    var title = $(item).attr('fieldname');
                    title = title ? title : '';

                    if (value) {
                        var latreg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;
                        if (latreg.test(value))
                            return $(item).attr('requiredmsg') ? $(item).attr('requiredmsg') : layui.admin.lang ? 'The latitude integer part is 0-90 and the decimal part is 0-6 bits.' : '纬度整数部分为0-90,小数部分为0到6位。';
                    }
                },
                //fun: function (value, item) {
                //    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                //        return '';
                //    if (admin.trimAll(value) !== ''&&typeof value  !== 'function')
                //        return $(item).attr('requiredmsg') ? $(item).attr('requiredmsg') : layui.admin.lang ? '必须是有效方法。' : '必须是有效方法。';
                //},
                //obj: function (value, item) {
                //    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                //        return '';

                //    if (admin.trimAll(value) !== '' && !admin.hasObject(admin.trimAll(value)))
                //        return $(item).attr('requiredmsg') ? $(item).attr('requiredmsg') : layui.admin.lang ? '必须是有效对象。' : '必须是有效对象。';
                //},
                int: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value) {
                        value = $.trim(value);

                        var title = $(item).attr('fieldname');
                        title = title ? title : '';

                        if (!reForm.regular.int.test(value))
                            return title + (layui.admin.lang ? " only integers can be integer." : '只能输入整数。');

                        var intVal = parseInt(value);
                        if (intVal < $(item).attr('minVal'))
                            return title + (layui.admin.lang ? " can't be less than " : '不能小于') + $(item).attr('minVal') + (layui.admin.lang ? '.' : '。');

                        if (intVal > $(item).attr('maxVal'))
                            return title + (layui.admin.lang ? " can't be greater than " : '不能大于') + $(item).attr('maxVal') + (layui.admin.lang ? '.' : '。');
                    }
                },
                decimal: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value) {
                        value = $.trim(value);

                        var title = $(item).attr('fieldname');
                        title = title ? title : '';

                        if (isNaN(value))
                            return title + (layui.admin.lang ? " only numbers can be entered." : '只能输入数字。');

                        var decimalVal = parseFloat(value);
                        if (decimalVal < $(item).attr('minVal'))
                            return title + (layui.admin.lang ? " can't be less than " : '不能小于') + $(item).attr('minVal') + (layui.admin.lang ? '.' : '。');

                        if (decimalVal > $(item).attr('maxVal'))
                            return title + (layui.admin.lang ? " can't be greater than " : '不能大于') + $(item).attr('maxVal') + (layui.admin.lang ? '.' : '。');

                        var decimalPlace = value.length - value.indexOf('.') - 1;
                        if (value.indexOf('.') > -1 && decimalPlace > $(item).attr('decimalPlace'))
                            return title + (layui.admin.lang ? " no more than " : '不能超过') + $(item).attr('decimalPlace') + (layui.admin.lang ? " decimal places. " : '位小数。');
                    }
                },
                chinese: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value) {
                        value = $.trim(value);

                        var title = $(item).attr('fieldname');
                        title = title ? title : '';

                        if (!reForm.regular.chinese.test(value))
                            return title + '只能输入中文汉字！';

                        var vLen = reForm.trimAll(value).length;
                        if (vLen < $(item).attr('minLen'))
                            return title + '字数不能小于' + $(item).attr('minLen') + '！';

                        if (vLen > $(item).attr('maxLen'))
                            return title + '字数不能大于' + $(item).attr('maxLen') + '！';
                    }
                },
                email: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value && !reForm.regular.email.test($.trim(value)))
                        return layui.admin.lang ? " Please enter the correct e-mail. " : '请输入正确的电子邮箱。';
                },
                phone: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value && !reForm.regular.phone.test($.trim(value)))
                        return layui.admin.lang ? " Please enter the correct mobile phone number. " : '请输入正确的手机号码。';
                },
                telephone: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value && !reForm.regular.telephone.test($.trim(value)))
                        return layui.admin.lang ? " Please enter the correct landline. " : '请输入正确的固定电话。';
                },
                url: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value && !reForm.regular.url.test($.trim(value)))
                        return layui.admin.lang ? " Please enter the correct address. " : '请输入正确的网址。';
                },
                regular: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (value) {
                        value = $.trim(value);

                        if (value && (value.substr(value.length - 1) === '/' || value.substr(0, 1) === '/'))
                            return '请输入正确的正则表达式，无需首位"/"！';
                    }
                },
                dateTime: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    if (!reForm.regular.dateTime.test($.trim(value)))
                        return layui.admin.lang ? " Please enter the correct date. " : '请输入正确的日期。';
                },
                checked: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    var title = $(item).attr('fieldname');
                    title = title ? title : '';

                    var checkedLen = $(item).find('input:checked').length;
                    if (checkedLen === 0)
                        return $(item).attr('choosemsg') ? $(item).attr('choosemsg') : (layui.admin.lang ? " Please choose " : '请选择') + title + (layui.admin.lang ? "." : '。');

                    var minChecked = $(item).attr('minChecked');
                    if (checkedLen < minChecked)
                        return title + '最少需要选中' + minChecked + '项！';

                    var maxChecked = $(item).attr('maxChecked');
                    if (checkedLen > maxChecked)
                        return title + '最多只能选中' + maxChecked + '项！';
                },
                selected: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    var title = $(item).attr('fieldname');
                    title = title ? title : '';
                    value = $.trim(value);
                    if (!value || value === '')
                        return $(item).attr('choosemsg') ? $(item).attr('choosemsg') : ((layui.admin.lang ? " Please choose " : '请选择') + title + (layui.admin.lang ? "." : '。'));
                },
                selects: function (value, item) {
                    if ($(item).closest('[reitemid]').attr('noverify') !== undefined)
                        return '';

                    var oldItem = $(item).parent().parent().prev();
                    var title = oldItem.attr('fieldname');
                    title = title ? title : '';

                    var checkedLen = value ? value.split(',').length : 0;
                    if (checkedLen === 0)
                        return oldItem.attr('choosemsg') ? oldItem.attr('choosemsg') : ((layui.admin.lang ? " Please choose " : '请选择') + title + (layui.admin.lang ? "." : '。'));

                    var minChecked = oldItem.attr('minChecked');
                    if (checkedLen < minChecked)
                        return title + '最少需要选中' + minChecked + '项！';

                    var maxChecked = oldItem.attr('maxChecked');
                    if (checkedLen > maxChecked)
                        return title + '最多只能选中' + maxChecked + '项！';
                }
            }

            , elementTypeSetting: ['string', 'textArea', 'imgArea', 'decimal', 'int', 'phoneNumber', 'telephoneNumber', 'email', 'dateTime', 'radio', 'checkbox', 'select', 'selects', 'password', 'hidden', 'switch', 'url', 'chinese', 'json', 'uuid', 'sysUser', 'sysTime', 'textEdit', 'editor', 'uploadImage', 'uploadFile']
            , elementTypeSettingName: ['单行输入', '多行输入', '拍照', '数字', '整数', '手机号码', '固定电话', '电子邮箱', '日期', '单项选择', '多项选择', '下拉列表', '下拉多选', '密码', '隐藏值', '开关', '网址', '中文', '对象', 'ID', '系统用户', '系统时间', '描述', '编辑器', '上传图片', '上传文件']
            , elementTypeSettingTemplate: ['textRow', 'textArea', 'imgArea', 'textCell', 'textCell', 'textCell', 'textCell', 'textCell', 'dateTime', 'radio', 'checkbox', 'select', 'selects', 'password', 'hidden', 'switch', 'textRow', 'textRow', 'json', 'uuid', 'sysUser', 'sysTime', 'textEdit', 'editor', 'uploadImage', 'uploadFile']

            , rotateImg: function (img, direction, canvas) {
                //alert(img);
                //最小与最大旋转方向，图片旋转4次后回到原方向
                var min_step = 0;
                var max_step = 3;
                //var img = document.getElementById(pid);
                if (img === undefined) return;
                //img的高度和宽度不能在img元素隐藏后获取，否则会出错
                var height = img.height;
                var width = img.width;
                var step = 2;

                if (direction === 'right') {
                    step++;
                    //旋转到原位置，即超过最大值
                    step > max_step && (step = min_step);
                } else {
                    step--;
                    step < min_step && (step = max_step);
                }
                var ctx = canvas.getContext('2d');
                //旋转角度以弧度值为参数
                var degree = step * 90 * Math.PI / 180;
                switch (step) {
                    case 0:
                        canvas.width = width;
                        canvas.height = height;
                        ctx.drawImage(img, 0, 0);
                        break;
                    case 1:
                        canvas.width = height;
                        canvas.height = width;
                        ctx.rotate(degree);
                        ctx.drawImage(img, 0, -height);
                        break;
                    case 2:
                        canvas.width = width;
                        canvas.height = height;
                        ctx.rotate(degree);
                        ctx.drawImage(img, -width, -height);
                        break;
                    case 3:
                        canvas.width = height;
                        canvas.height = width;
                        ctx.rotate(degree);
                        ctx.drawImage(img, -width, 0);
                        break;
                }
                //return ctx;
            },
            getCompressRate: function (allowMaxSize, fileSize) { //计算压缩比率，size单位为MB
                var compressRate = 1;

                if (fileSize / allowMaxSize > 4) {
                    compressRate = 0.5;
                } else if (fileSize / allowMaxSize > 3) {
                    compressRate = 0.6;
                } else if (fileSize / allowMaxSize > 2) {
                    compressRate = 0.7;
                } else if (fileSize > allowMaxSize) {
                    compressRate = 0.8;
                } else {
                    compressRate = 0.9;
                }

                return compressRate;
            }
            , setItemHide: function (formSign, obj) {
                if (obj.attr('relevanceshow'))
                    $.each(obj.attr('relevanceshow').split(','), function (k, v) {
                        $(formSign + '[reitemid="' + v + '"]').show();
                        $(formSign + '[reitemid="' + v + '"]').removeAttr('noverify', '');
                    });
                if (obj.attr('relevancehide'))
                    $.each(obj.attr('relevancehide').split(','), function (k, v) {
                        $(formSign + '[reitemid="' + v + '"]').hide();
                        $(formSign + '[reitemid="' + v + '"]').attr('noverify', '');
                    });
            }
            , bindSelects: function (options) {
                debugger
                console.log("12132139999",options);
                var othis = $('[xm-select="' + options.selectId + '"]');

                othis.attr('xm-select-skin', 'default');

                if (options.search)
                    othis.attr('xm-select-search', '');

                var html = '<option value="">' + (options.optionTip||'请选择') + '</option>';
                var loadDate = function (data) {
                    var textKey = options.optionText;
                    var textKeys = textKey ? textKey.split(',') : null;

                    layui.each(data, function (idx, item) {

                        html += '<option value="' + item[options.optionKey || 'Member'] + '"';
                        if (admin.hasObject(options.initData) && options.initData[options.name] !== undefined
                            && (item[options.optionKey || 'Member'] === options.initData[options.name]
                                || $.inArray(item[options.optionKey || 'Member'], options.initData[options.name] ? options.initData[options.name].split(',') : []) > -1))
                            html += ' selected="selected" ';
                        else if (options.initSelect
                            && (item[options.optionKey || 'Member'] === options.initSelect
                                || $.inArray(item[options.optionKey || 'Member'], options.initSelect.split(',')) > -1))
                            html += ' selected="selected" ';

                        html += '>';
                        var text = '';
                        var texts = [];
                        if (textKeys && textKeys.length > 0) {
                            $.each(textKeys, function (k, v) {
                                texts.push(item[v + admin.lang] || item[v] || item['MemberName' + admin.lang]);
                            });
                            text = texts.join(' - ');
                        }
                        else
                            text = item[textKey + admin.lang] || item[textKey] || item['MemberName' + admin.lang];


                        html += text;
                        html += '</option>';
                    });

                    othis.children().remove();
                    othis.append(html);
                    formSelects.render(options.selectId, { radio: options.radio });

                    if (admin.hasObject(options.initData) && options.initData[options.name] !== undefined) {
                        formSelects.value(options.selectId, options.initData[options.name] ? options.initData[options.name].split(',') : []);
                    }
                    else if (options.initSelect) {
                        formSelects.value(options.selectId, options.initSelect.split(','));
                    }
                };
                
                if (options.optionsApi && options.optionKey && options.optionText) {

                    var where = {};
                    if (options.optionsWhere) {
                        try {
                            if (typeof options.optionsWhere === 'string')
                                options.optionsWhere = admin.funObj(options.optionsWhere, options.initData);
                            if (options.optionsWhere.SearchWhere)
                                options.optionsWhere.SearchWhere = JSON.stringify(options.optionsWhere.SearchWhere);

                            where = options.optionsWhere;

                        } catch (e) {
                            console.log(e);
                        }
                    }

                    admin.req({
                        type: 'post'
                        , url: options.optionsApi
                        , data: where
                        , done: function (res) {
                            loadDate(res.data);
                        }
                    });
                }
                else if (options.optionsSource) {
                    admin.getDicParams(options.optionsSource, function (data) {
                        loadDate(data);
                    });
                } else if (options.optionsLocalData) {
                    loadDate(options.optionsLocalData);
                } else {
                    var strArray = admin.optionsArray(options.options);
                    $.each(strArray, function (k, v) {
                        html += '<option value="' + v + '"';
                        if (admin.hasObject(options.initData) && options.initData[options.name] !== undefined && (v === options.initData[options.name] || $.inArray(v, options.initData[options.name] ? options.initData[options.name].split(',') : []) > -1))
                            html += ' selected="selected" ';
                        else if (options.initSelect && (v === options.initSelect || $.inArray(v, options.initSelect.split(',')) > -1))
                            html += ' selected="selected" ';
                        html += '>';
                        html += v;
                        html += '</option>';
                    });
                    othis.children().remove();
                    othis.append(html);

                    formSelects.render(options.selectId, { radio: options.radio });

                    if (admin.hasObject(options.initData) && options.initData[options.name] !== undefined)
                        formSelects.value(options.selectId, options.initData[options.name] ? options.initData[options.name].split(',') : []);
                    else if (options.initSelect)
                        formSelects.value(options.selectId, options.initSelect.split(','));
                }
                if (options.on)
                    formSelects.on(options.selectId, function (id, vals, val, isAdd, isDisabled) {
                        options.on(id, vals, val, isAdd, isDisabled);
                    }, true);
            }
            , bindSelect: function (options) {
                
                var othis = $('[lay-filter="' + options.filter + '"]');

                if (options.search !== false)
                    othis.attr('lay-search', '');

                var html = '<option value="">' + (options.optionTip || '请选择') + '</option>';
                var loadDate = function (data) {

                    var textKey = options.optionText;
                    var textKeys = textKey ? textKey.split(',') : null;

                    layui.each(data, function (idx, item) {
                        html += '<option value="' + item[options.optionKey || 'Member'] + '"';

                        if (admin.hasObject(options.initData) && options.initData[options.name] !== undefined && item[options.optionKey || 'Member'] === options.initData[options.name]) {
                            html += ' selected ';
                        } else if (options.initSelect && item[options.optionKey || 'Member'] === options.initSelect) {
                            html += ' selected ';
                        }

                        html += '>';
                        var text = '';
                        var texts = [];
                        if (textKeys && textKeys.length > 0) {
                            $.each(textKeys, function (k, v) {
                                texts.push(item[v + admin.lang] || item[v] || item['MemberName' + admin.lang]);
                            });
                            text = texts.join(' - ');
                        }
                        else
                            text = item[textKey + admin.lang] || item[textKey] || item['MemberName' + admin.lang];


                        html += text;
                        html += '</option>';
                    });

                    othis.children().remove();
                    othis.append(html);
                    form.render();
                };

                if (options.optionsApi && options.optionKey && options.optionText) {

                    var where = {};
                    if (options.optionsWhere) {
                        try {
                            if (typeof options.optionsWhere === 'string')
                                options.optionsWhere = admin.funObj(options.optionsWhere, options.initData);
                            if (options.optionsWhere.SearchWhere)
                                options.optionsWhere.SearchWhere = JSON.stringify(options.optionsWhere.SearchWhere);

                            where = options.optionsWhere;

                        } catch (e) {
                            console.log(e);
                        }
                    }
                    console.log("1231231231", where);
                    admin.req({
                        type: 'post'
                        , url: options.optionsApi
                        , data: where
                        , done: function (res) {
                            console.log(res.data)
                            loadDate(res.data);
                        }
                    });
                }
                else if (options.optionsSource) {
                    admin.getDicParams(options.optionsSource, function (data) { loadDate(data); });
                } else {
                    var strArray = admin.optionsArray(options.options);
                    $.each(strArray, function (k, v) {
                        html += '<option value="' + v + '"';
                        if (admin.hasObject(options.initData) && v === options.initData[options.name])
                            html += ' selected ';
                        else if (options.initSelect && v === options.initSelect) {
                            html += ' selected ';
                        }
                        html += '>';
                        html += v;
                        html += '</option>';
                    });
                    othis.children().remove();
                    othis.append(html);
                }

                if (options.on) {
                    form.on('select(' + options.filter + ')', function (obj) {
                        typeof options.on === 'function' && options.on.call(this, obj);
                    });
                }
            }
            , bindFormHtml: function (jsonData, initData, sign) {
                if (!admin.hasObject(jsonData)) return;

                if (jsonData.array)
                    $.each(jsonData.array, function (idx, json) {
                        reForm.bindFormHtml(json, initData, sign);
                    });

                var debug = sign ? false : true;

                var formSign = sign ? '[lay-filter="' + sign + '"] ' : '';

                sign = sign || admin.uuid(10, 10);

                if (jsonData.itemData) {

                    if (jsonData.itemData.initHide === true) {
                        if (!debug) {
                            $(formSign + '[reitemid="' + jsonData.itemId + '"]').hide();
                        }
                        else
                            $(formSign + '[reitemid="' + jsonData.itemId + '"]').css({ 'background-color': '#F0F0F0', 'min-height': '37px' });

                        $(formSign + '[reitemid="' + jsonData.itemId + '"]').attr('noverify', '');

                    } else if (jsonData.itemData.initHide === false) {
                        if (!debug) {
                            $(formSign + '[reitemid="' + jsonData.itemId + '"]').show();
                        }
                        else
                            $(formSign + '[reitemid="' + jsonData.itemId + '"]').css({ 'background-color': '', 'min-height': '' });

                        $(formSign + '[reitemid="' + jsonData.itemId + '"]').removeAttr('noverify');
                    }

                    var elementType = jsonData.itemData.elementType;

                    //绑定文本
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindtext]'), function () {

                        $(this).html(jsonData.itemData[$(this).attr('bindText') + admin.lang]);

                    });
                    //绑定name值
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindname]'), function () {

                        var name = jsonData.itemData.itemName;
                        if (!name || name === '') {
                            name = 'Name_' + admin.uuid(8, 16);
                            jsonData.itemData.itemName = name;
                        }

                        $(this).attr('name', name);

                        if (jsonData.itemData.defaultVal)
                            $(this).val(jsonData.itemData.defaultVal);

                        if (jsonData.itemData.condition)
                            $(this).attr('condition', jsonData.itemData.condition);
                        if (jsonData.itemData.compare)
                            $(this).attr('compare', jsonData.itemData.compare);

                    });
                    //绑定输入提示
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindplaceholder]'), function () {
                        $(this).attr('placeholder', jsonData.itemData[$(this).attr('bindplaceholder') + admin.lang]);
                    });
                    //绑定显示隐藏
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindhide]'), function () {
                        if (jsonData.itemData[$(this).attr('bindhide') + admin.lang])
                            $(this).removeClass('layui-hide');
                        else
                            $(this).addClass('layui-hide');
                    });
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindhidden]'), function () {
                        if (!debug) {
                            $(this).parent().parent().hide();
                            $(this).closest('[reitemid]').find('label').remove();
                        }
                        else
                            $(this).parent().parent().css({ 'background-color': '#F0F0F0', 'min-height': '37px' });
                    });
                    //绑定验证
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindverify]'), function () {

                        var verify = $(this);

                        verify.removeAttr('fieldName');
                        verify.attr('fieldName', jsonData.itemData['fieldName' + admin.lang]);

                        verify.removeAttr('lay-verify');
                        verify.removeAttr('_lay-verify');

                        verify.removeAttr('minLen');
                        verify.removeAttr('maxLen');
                        verify.removeAttr('minVal');
                        verify.removeAttr('maxVal');
                        verify.removeAttr('decimalPlace');
                        verify.removeAttr('minChecked');
                        verify.removeAttr('maxChecked');
                        verify.removeAttr('requiredMsg');
                        verify.removeAttr('requiredMsg_EN');
                        verify.removeAttr('chooseMsg');
                        verify.removeAttr('chooseMsg_EN');
                        verify.removeAttr('regular');
                        verify.removeAttr('regularMsg');
                        verify.removeAttr('regularMsg_EN');

                        var required = jsonData.itemData.required;
                        var choose = jsonData.itemData.choose;

                        if (required && (elementType === 'string' || elementType === 'textArea' || elementType === 'password' || elementType === 'uploadImage' || elementType === 'uploadFile'))
                            verify.attr('lay-verify', 'required');
                        else if (required && elementType === 'editor')
                            verify.attr('lay-verify', 'editor');
                        else if (required && elementType === 'int')
                            verify.attr('lay-verify', 'required|int');
                        else if (required && elementType === 'decimal')
                            verify.attr('lay-verify', 'required|decimal');
                        else if (required && elementType === 'chinese')
                            verify.attr('lay-verify', 'required|chinese');
                        else if (required && elementType === 'email')
                            verify.attr('lay-verify', 'required|email');
                        else if (required && elementType === 'phoneNumber')
                            verify.attr('lay-verify', 'required|phone');
                        else if (required && elementType === 'telephoneNumber')
                            verify.attr('lay-verify', 'required|telephone');
                        else if (required && elementType === 'url')
                            verify.attr('lay-verify', 'required|url');

                        else if (choose && elementType === 'dateTime')
                            verify.attr('lay-verify', 'required');//|dateTime
                        else if (choose && elementType === 'select')
                            verify.attr('lay-verify', 'selected');
                        else if (choose && elementType === 'selects')
                            verify.attr('lay-verify', 'selects');
                        else if (choose)
                            verify.attr('lay-verify', 'checked');

                        else if (!required && (elementType === 'string' || elementType === 'textArea' || elementType === 'password' || elementType === 'uploadImage' || elementType === 'uploadFile'))
                            verify.attr('lay-verify', 'fillRequired');
                        else if (!required && elementType === 'editor')
                            verify.attr('lay-verify', 'fillEditor');
                        else if (!required && elementType === 'int')
                            verify.attr('lay-verify', 'int');
                        else if (!required && elementType === 'decimal')
                            verify.attr('lay-verify', 'decimal');
                        else if (!required && elementType === 'chinese')
                            verify.attr('lay-verify', 'chinese');
                        else if (!required && elementType === 'email')
                            verify.attr('lay-verify', 'email');
                        else if (!required && elementType === 'phoneNumber')
                            verify.attr('lay-verify', 'phone');
                        else if (!required && elementType === 'telephoneNumber')
                            verify.attr('lay-verify', 'telephone');
                        else if (!required && elementType === 'url')
                            verify.attr('lay-verify', 'url');

                        //else if (!choose && elementType === 'dateTime')
                        //    verify.attr('lay-verify', 'dateTime');

                        if (!(elementType === 'editor' || elementType === 'uploadImage' || elementType === 'uploadFile' || elementType === 'radio' || elementType === 'checkbox'))
                            verify.attr('lay-verType', 'tips');

                        $.each(jsonData.itemData, function (k, v) {
                            if ((k === 'minLen' || k === 'maxLen' || k === 'minVal' || k === 'maxVal' || k === 'decimalPlace' || k === 'minChecked' || k === 'maxChecked' || k === 'requiredMsg' || k === 'requiredMsg_EN' || k === 'chooseMsg' || k === 'chooseMsg_EN' || k === 'regular' || k === 'regularMsg' || k === 'regularMsg_EN') && v !== '') {
                                verify.attr(k, v);
                            }
                        });
                    });
                    //绑定单选、复选
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindcheckbox]'), function () {

                        var name = jsonData.itemData.itemName;
                        if (!name || name === '') {
                            name = 'Name_' + admin.uuid(8, 16);
                            jsonData.itemData.itemName = name;
                        }

                        var filter = sign + '-' + jsonData.itemData.itemName;

                        var othis = $(this);
                        var template = othis.children(':first');
                        if (template.length === 0) {
                            othis.append('<input type="' + jsonData.itemData.elementType + '">');
                            template = othis.children(':first');
                        }
                        var html = '';

                        var relevanceItem = jsonData.itemData.relevanceItem ? typeof jsonData.itemData.relevanceItem === 'string' ? JSON.parse(jsonData.itemData.relevanceItem) : jsonData.itemData.relevanceItem : [];

                        if (jsonData.itemData.optionsSource) {
                            admin.getDicParams(jsonData.itemData.optionsSource, function (data) {
                                layui.each(data, function (idx, item) {
                                    template.removeAttr('checked');
                                    template.removeAttr('lay-skin');
                                    template.removeAttr('relevanceshow');
                                    template.removeAttr('relevancehide');

                                    if (jsonData.itemData.condition)
                                        template.attr('condition', jsonData.itemData.condition);
                                    if (jsonData.itemData.compare)
                                        template.attr('compare', jsonData.itemData.compare);

                                    template.attr('name', jsonData.itemData.itemName).attr('lay-filter', filter).attr('title', item['MemberName' + admin.lang]).val(item.Member);

                                    if (debug) {
                                        if (jsonData.itemData.optionsChecked && $.inArray(item.Member, jsonData.itemData.optionsChecked.split(',')) > -1)
                                            template.attr('checked', 'checked');
                                    } else {
                                        if (admin.hasObject(initData) && $.inArray(item.Member, initData[name] ? (initData[name] + '').split(',') : []) > -1)
                                            template.attr('checked', 'checked');
                                        else if (admin.hasObject(initData) && typeof initData[name] === undefined && jsonData.itemData.optionsChecked && $.inArray(item.Member, jsonData.itemData.optionsChecked.split(',')) > -1)
                                            template.attr('checked', 'checked');
                                        else if (!initData && jsonData.itemData.optionsChecked && $.inArray(item.Member, jsonData.itemData.optionsChecked.split(',')) > -1)
                                            template.attr('checked', 'checked');
                                    }

                                    if (admin.hasArray(relevanceItem))
                                        $.each(relevanceItem, function (idx, json) {
                                            if (json.item === item.Member) {
                                                if (json.relevanceShow)
                                                    template.attr('relevanceshow', json.relevanceShow);
                                                if (json.relevanceHide)
                                                    template.attr('relevancehide', json.relevanceHide);

                                                if (template.attr('checked')&&!debug)
                                                    setTimeout(function () {
                                                        reForm.setItemHide(formSign, $(formSign + '[reitemid="' + jsonData.itemId + '"] [value="' + item.Member + '"]'));
                                                    }, 200);

                                                return;
                                            }
                                        });


                                    if (jsonData.itemData.checkboxTheme === '1')
                                        template.attr('lay-skin', 'primary');

                                    html += template.prop('outerHTML');
                                });
                                othis.children().remove();
                                othis.append(html);
                                form.render();
                            });
                        } else {
                            var strArray = admin.optionsArray(jsonData.itemData.options);
                            $.each(strArray, function (k, v) {
                                template.removeAttr('checked');
                                template.removeAttr('lay-skin');
                                template.removeAttr('relevanceshow');
                                template.removeAttr('relevancehide');

                                if (jsonData.itemData.condition)
                                    template.attr('condition', jsonData.itemData.condition);
                                if (jsonData.itemData.compare)
                                    template.attr('compare', jsonData.itemData.compare);

                                template.attr('name', jsonData.itemData.itemName).attr('lay-filter', filter).attr('title', v).val(v);

                                if (debug) {
                                    if (jsonData.itemData.optionsChecked && $.inArray(v, jsonData.itemData.optionsChecked.split(',')) > -1)
                                        template.attr('checked', 'checked');
                                } else {
                                    if (admin.hasObject(initData) && $.inArray(v, initData[name] ? initData[name].split(',') : []) > -1)
                                        template.attr('checked', 'checked');
                                    else if (admin.hasObject(initData) && typeof initData[name] === undefined && jsonData.itemData.optionsChecked && $.inArray(item.Member, jsonData.itemData.optionsChecked.split(',')) > -1)
                                        template.attr('checked', 'checked');
                                    else if (!initData && jsonData.itemData.optionsChecked && $.inArray(v, jsonData.itemData.optionsChecked.split(',')) > -1)
                                        template.attr('checked', 'checked');
                                }

                                if (admin.hasArray(relevanceItem))
                                    $.each(relevanceItem, function (idx, json) {
                                        if (json.item === v) {
                                            if (json.relevanceShow)
                                                template.attr('relevanceshow', json.relevanceShow);
                                            if (json.relevanceHide)
                                                template.attr('relevancehide', json.relevanceHide);

                                            if (template.attr('checked') && !debug)
                                                setTimeout(function () {
                                                    reForm.setItemHide(formSign, $(formSign + '[reitemid="' + jsonData.itemId + '"] [value="' + v + '"]'));
                                                }, 200);

                                            return;
                                        }
                                    });

                                if (jsonData.itemData.checkboxTheme === '1')
                                    template.attr('lay-skin', 'primary');

                                html += template.prop('outerHTML');
                                //}
                            });
                            $(this).children().remove();
                            $(this).append(html);
                        }
                        
                        if (admin.hasArray(relevanceItem))
                            form.on('radio(' + filter + ')', function (data) {
                                reForm.setItemHide(formSign, $(this));
                                if (jsonData.itemData.event)
                                    typeof jsonData.itemData.event === 'function' && jsonData.itemData.event.call(this, obj);
                            });

                        if (jsonData.itemData.event) {
                            form.on(jsonData.itemData.elementType + '(' + filter + ')', function (obj) {

                                if (admin.hasArray(relevanceItem))
                                    reForm.setItemHide(formSign, $(this));

                                typeof jsonData.itemData.event === 'function' && jsonData.itemData.event.call(this, obj);
                            });
                        }
                    });
                    //下拉列表
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindselect]'), function () {
                        //console.log(123);
                        var filter = sign + '-' + jsonData.itemData.itemName;

                        if (debug) {
                            $(this).removeAttr('lay-search');
                            $(this).removeAttr('lay-filter');
                        }

                        $(this).attr('lay-filter', filter);
                        var options = {
                            search: jsonData.itemData.optionsSearch
                            , options: jsonData.itemData.options
                            , optionsSource: jsonData.itemData.optionsSource
                            , optionsApi: jsonData.itemData.optionsApi
                            , optionsWhere: jsonData.itemData.optionsWhere
                            , optionKey: jsonData.itemData.optionKey || ''
                            , optionText: jsonData.itemData.optionText || ''
                            , optionTip: jsonData.itemData['optionTip' + admin.lang]
                            , initData: initData
                            , initSelect: jsonData.itemData.optionsChecked
                            , filter: filter
                            , name: jsonData.itemData.itemName
                            , on: jsonData.itemData.event
                        };

                        reForm.bindSelect(options);
                    });
                    //绑定下拉多选
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindselects]'), function () {
                        console.log(12345);
                        var selectId = sign + '-' + jsonData.itemData.itemName;

                        if (debug) {
                            $(this).removeAttr('xm-select-search');
                            $(this).removeAttr('xm-select-skin');
                        }

                        $(this).attr('xm-select', selectId);
                        var options = {
                            search: jsonData.itemData.optionsSearch
                            , options: jsonData.itemData.options
                            , optionsLocalData: jsonData.itemData.optionsLocalData
                            , optionsSource: jsonData.itemData.optionsSource
                            , optionsApi: jsonData.itemData.optionsApi
                            , optionsWhere: jsonData.itemData.optionsWhere
                            , optionKey: jsonData.itemData.optionKey || ''
                            , optionText: jsonData.itemData.optionText || ''
                            , optionTip: jsonData.itemData['optionTip']
                            , initData: initData
                            , initSelect: jsonData.itemData.optionsChecked
                            , selectId: selectId
                            , name: jsonData.itemData.itemName
                            , on: jsonData.itemData.event
                        };
                        reForm.bindSelects(options);

                    });
                    //绑定开关
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindswitch]'), function () {
                        var filter = sign + '-' + jsonData.itemData.itemName;

                        $(this).attr('lay-filter', filter);

                        $(this).attr('lay-skin', 'switch').attr('lay-text', jsonData.itemData['switchText' + admin.lang]);
                        $(this).prop('checked', false);
                        if (jsonData.itemData.switchDefault)
                            $(this).prop('checked', true);
                    });
                    //绑定日期
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [binddatetime]'), function () {

                        var filter = sign + '-' + jsonData.itemData.itemName;

                        if (debug) {

                            filter = admin.uuid(10, 10) + '-' + jsonData.itemData.itemName;

                            $(this).removeAttr('lay-key');
                            $(this).after($(this).prop('outerHTML'));
                            $(this).next().attr('lay-filter', filter);
                            $(this).remove();
                        }

                        $(this).attr('lay-filter', filter);
                        $(this).attr('nofocus','');
                        laydate.render({
                            elem: '[lay-filter="' + filter + '"]',
                            trigger: 'click',
                            type: jsonData.itemData.dateType,
                            format: jsonData.itemData.dateFormat
                        });
                    });
                    //绑定描述
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"][bindtextedit]'), function () {
                        $(this).html(jsonData.itemData.editText);
                    });
                    //绑定编辑器
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindeditor]'), function () {
                        var filter = sign + '-' + jsonData.itemData.itemName;

                        if (debug)
                            filter = admin.uuid(10, 10) + '-' + jsonData.itemData.itemName;

                        $(this).attr('id', filter);
                        $(this).attr('retype', 'editor');

                        reForm.editor[filter] = reForm.initEditor({
                            editorId: filter
                            , tools: jsonData.itemData.editorTools
                            , height: jsonData.itemData.editorHeight
                            , uploadApi: jsonData.itemData.uploadApi
                            , uploadFolder: jsonData.itemData.uploadFolder
                        });
                    });
                    //绑定图片上传
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"][binduploadimage]'), function () {
                        var filter = sign + '-' + jsonData.itemData.itemName;

                        if (debug)
                            filter = admin.uuid(10, 10) + '-' + jsonData.itemData.itemName;

                        var browse = filter + '-browse'
                            , upload = filter + '-upload'
                            , view = filter + '-view';

                        $(this).find('[uploadview] input:hidden').attr('id', filter);
                        $(this).find('[uploadview] img').attr('id', view);
                        $(this).find('[browsebtn]').attr('id', browse).val('浏览');
                        $(this).find('[uploadbtn]').attr('id', upload).val('上传');

                        if (admin.hasObject(initData) && initData[jsonData.itemData.itemName]) {
                            var url = initData[jsonData.itemData.itemName];
                            $('#' + view).attr('src', layui.setter.fileApi + url.substr(0, url.indexOf('\\'))).attr('title', url.indexOf('\\') + 1);
                        }

                        reForm.initUpload({
                            elem: '#' + browse
                            , accept: 'images'
                            , size: jsonData.itemData.fileSize || 1024
                            , exts: jsonData.itemData.fileExts || 'jpg|png'
                            , bindAction: '#' + upload
                            , custom: {
                                uploadApi: jsonData.itemData.uploadApi
                                , uploadFolder: jsonData.itemData.uploadFolder
                                , fun: {
                                    choose: function (index, file, result) {
                                        $('#' + filter).val('');
                                        $('#' + view).attr('src', result).attr('title', file.name);
                                        $('#' + upload).show();
                                    }
                                    , before: function (obj) {
                                        $('#' + view).removeAttr('src').removeAttr('title');
                                    }
                                    , done: function (res) {
                                        $('#' + filter).val(res.result + '\\' + res.fileName);
                                        $('#' + view).attr('src', layui.setter.fileApi + res.result).attr('title', res.fileName);
                                        $('#' + upload).hide();
                                    }
                                    , error: function () {
                                        $('#' + upload).hide();
                                    }
                                }
                            }
                        });
                    });
                    //绑定拍照
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"] [bindimgarea]'), function () {
                        if ($(this).parent().find('.imgArea').html() === undefined)
                            $(this).after('<ul class="imgArea"></ul><button type="button" class="layui-btn layui-btn-normal" photobtn>拍照</button>');

                    });
                    //绑定文件上传
                    $.each($(formSign + '[reitemid="' + jsonData.itemId + '"][binduploadfile]'), function () {
                        var filter = sign + '-' + jsonData.itemData.itemName;

                        if (debug)
                            filter = admin.uuid(10, 10) + '-' + jsonData.itemData.itemName;

                        var browse = filter + '-browse'
                            , upload = filter + '-upload'
                            , view = filter + '-view';

                        $(this).find('[uploadview] input:hidden').attr('id', filter);
                        $(this).find('[uploadview] input:text').attr('id', view);
                        $(this).find('[browsebtn]').attr('id', browse).val('浏览');
                        $(this).find('[uploadbtn]').attr('id', upload).val('上传');

                        reForm.initUpload({
                            elem: '#' + browse
                            , accept: 'file'
                            , size: jsonData.itemData.fileSize || 2014
                            , exts: jsonData.itemData.fileExts || 'jpg|png|pdf|docx|xlsx'
                            , bindAction: '#' + upload
                            , custom: {
                                uploadApi: jsonData.itemData.uploadApi
                                , uploadFolder: jsonData.itemData.uploadFolder
                                , fun: {
                                    choose: function (index, file, result) {
                                        $('#' + filter).val('');
                                        $('#' + view).val(file.name);
                                        $('#' + upload).show();
                                    }
                                    , before: function (obj) {
                                        $('#' + view).val('');
                                    }
                                    , done: function (res) {
                                        $('#' + filter).val(res.result); //+ '\\' + res.fileName
                                        $('#' + view).val(res.result);// + '\\' + res.fileName
                                        $('#' + upload).hide();
                                    }
                                    , error: function () {
                                        $('#' + upload).hide();
                                    }
                                }
                            }
                        });
                    });
                }
            }

            , layoutChange: function (jsonObj, layout, merge, elementTypeSettingData) {
                //merge 1 合并 2 拆分 0 自动
                var elementType = jsonObj.itemData.elementType;

                var defaultlayout = elementTypeSettingData[elementType + ''].layout;

                if (defaultlayout !== '') {
                    jsonObj.itemData.layout = layout;

                    if (layout === 'row' && merge === 1 && defaultlayout === 'cell') {
                        jsonObj.itemData.layout = 'cell';
                    }

                    var row = jsonObj.child.length;

                    if (layout === 'row' && (merge === 1 && defaultlayout === 'row' || merge === 0) && row === 3 && jsonObj.itemData['tipText' + admin.lang] !== undefined) {
                        jsonObj.child[1].child.push(admin.jsonClone(jsonObj.child[2]));
                        jsonObj.child.splice(2, 1);
                    }

                    if (layout === 'cell' && row === 2 && jsonObj.itemData['tipText' + admin.lang] !== undefined) {
                        jsonObj.child.push(admin.jsonClone(jsonObj.child[1].child[1]));
                        jsonObj.child[1].child.splice(1, 1);
                    }
                }

                if (merge === 2) {
                    jsonObj.itemData.layout = '';
                    jsonObj.class = 'layui-inline';
                } else {
                    jsonObj.class = 'layui-form-item';
                }

                if (elementType === 'uploadImage') {
                    jsonObj.child[1].class = 'layui-inline';
                }
                else if (elementType === 'radio' || elementType === 'checkbox'  || elementType === 'editor' || elementType === 'uploadFile' || elementType === 'imgArea') {
                    jsonObj.child[1].class = 'layui-input-block';
                }
                else if (layout === 'row' && (merge === 1 && defaultlayout === 'row' || merge === 0) && defaultlayout !== '') {
                    jsonObj.child[1].class = 'layui-input-block';
                }
                else if (elementType !== 'textEdit'){
                    jsonObj.child[1].class = 'layui-input-inline';
                }
            }
            , updateFormConfig: function (jsonList, elementTypeSettingData, elementTypeTemplateData, marge, type) {
                //更新表单数据
                for (var i = 0; i < jsonList.length; i++) {
                    var json = jsonList[i];

                    if (!admin.hasObject(json))
                        return;

                    if (json.array)
                        reForm.updateFormConfig(json.array, elementTypeSettingData, elementTypeTemplateData, true, type);

                    if (json.itemData) {
                        var defaultTemplate = elementTypeTemplateData[reForm.elementTypeSettingTemplate[$.inArray(json.itemData.elementType, reForm.elementTypeSetting)]];

                        if (!defaultTemplate) {
                            jsonList.splice(i, 1);
                            i--;
                            continue;
                        }
                        var newTemplate = admin.jsonClone(defaultTemplate);

                        newTemplate.itemId = json.itemId;

                        if (json.relevanceId)
                            newTemplate.relevanceId = json.relevanceId;

                        newTemplate.itemData = admin.jsonClone(json.itemData);

                        if (marge)
                            reForm.layoutChange(newTemplate, 'cell', 2, elementTypeSettingData);
                        else if (type !== 2)
                            reForm.layoutChange(newTemplate, newTemplate.itemData.layout, 0, elementTypeSettingData);

                        jsonList.splice(i, 1, newTemplate);

                        var objKeys = Object.keys(json.itemData);
                        var defaultSetting = elementTypeSettingData[json.itemData.elementType];
                        if (!defaultSetting) {
                            jsonList.splice(i, 1);
                            i--;
                            continue;
                        }

                        var defaultSettingKeys = Object.keys(defaultSetting);
                        $.each(objKeys, function (k, v) {
                            if ($.inArray(v, defaultSettingKeys) === -1)
                                delete json.itemData[v];
                        });

                        jsonList[i].itemData = $.extend({}, elementTypeSettingData[json.itemData.elementType], json.itemData);

                    }
                }
            }
            , getFormFields: function (jsonList) {
                var list = [];
                $.each(jsonList, function (idx, json) {
                    if (json.array)
                        $.merge(list, reForm.getFormFields(json.array));

                    if (json.itemData)
                        list.push(admin.jsonClone(json.itemData));

                });
                return list;
            }
            , updateFormFields: function (formFields, elementTypeSettingData) {
                for (var i = 0; i < formFields.length; i++) {
                    var json = formFields[i];
                    var objKeys = Object.keys(json);

                    var defaultSetting = elementTypeSettingData[json.elementType];

                    if (!defaultSetting) {
                        formFields.splice(i, 1);
                        i = i - 1;
                        continue;
                    }
                    var defaultSettingKeys = Object.keys(defaultSetting);
                    $.each(objKeys, function (k, v) {
                        if ($.inArray(v, defaultSettingKeys) === -1) delete json[v];
                    });
                }
            }

            , initEditor: function (options) {
                var tools = [
                    'strong' //加粗
                    , 'italic' //斜体
                    , 'underline' //下划线
                    , 'del' //删除线

                    , '|' //分割线

                    , 'left' //左对齐
                    , 'center' //居中对齐
                    , 'right' //右对齐
                    , 'link' //超链接
                    , 'unlink' //清除链接
                ];

                if (options.tools)
                    tools.push.apply(tools, options.tools.split(','));

                var editorOptions = {
                    tool: tools
                    , height: options.height || 400
                };

                if (options.uploadApi)
                    editorOptions.uploadImage = {
                        headers: {
                            Authorization: 'Bearer ' + (layui.data(layui.setter.tableName)[layui.setter.request.tokenName] || '')
                        }
                        , url: layui.setter.fileApi + options.uploadApi
                        , data: { source: options.uploadFolder || '' }
                    };

                var editor = layedit.build(options.editorId, editorOptions);

                //编辑器外部操作
                var fun = $.extend({
                    content: function () {
                        return layedit.getContent(editor); //获取编辑器内容
                    }
                    , setContent: function (html) {
                        layedit.setContent(editor, html, false);
                    }
                    , text: function () {
                        return layedit.getText(editor); //获取编辑器纯文本内容
                    }
                    , selection: function () {
                        return layedit.getSelection(editor);
                    }
                    , sync: function () {
                        layedit.sync(editor);
                    }
                }, options.fun);

                return fun;
            }
            , initUpload: function (options) {

                var custom = options.custom;

                upload.render($.extend({
                    headers: {
                        Authorization: 'Bearer ' + (layui.data(layui.setter.tableName)[layui.setter.request.tokenName] || '')
                    }
                    , url: layui.setter.fileApi + custom.uploadApi
                    , data: { source: options.uploadFolder || '' }
                    , auto: false
                    , choose: function (obj) {
                        obj.preview(function (index, file, result) {

                            custom.fun && typeof custom.fun.choose && custom.fun.choose.call(this, index, file, result);
                        });
                    }
                    , before: function (obj) {
                        custom.fun && typeof custom.fun.before && custom.fun.before.call(this, obj);
                    }
                    , done: function (res) {
                        custom.fun && typeof custom.fun.done && custom.fun.done.call(this, res);
                    }
                    , error: function () {
                        custom.fun && typeof custom.fun.error && custom.fun.error.call(this);
                    }
                }, options));
            }
        };

    exports('reForm', reForm);
});